package com.daiyang.campus_lucky_draw.service.impl;

import com.daiyang.campus_lucky_draw.common.error.ServiceErrorCodeConstants;
import com.daiyang.campus_lucky_draw.common.exception.ServiceException;
import com.daiyang.campus_lucky_draw.service.PictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class PictureServiceImpl implements PictureService {
    @Value("${pic.local-path}")

    private String picLocalPath;
    @Override
    public String savePicture(MultipartFile pic) {
        File dir = new File(picLocalPath);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        // 获取⽂件名
        String fileName = pic.getOriginalFilename();
        assert fileName != null;
        // 获取⽂件后缀名。
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 也可以在这⾥添加判断语句，规定特定格式的图⽚才能上传，否则拒绝保存。
        // ⽣成随机数防⽌图⽚重名
        fileName = UUID.randomUUID() + suffixName;
        try {
            pic.transferTo(new File(picLocalPath + "/" + fileName));
        } catch (IOException e) {
            throw new
                    ServiceException(ServiceErrorCodeConstants.UPLOAD_PIC_ERROR);
        }
        return fileName;
    }
}

